/*
 * // Bristleback plugin - Copyright (c) 2010 bristleback.googlecode.com
 * // ---------------------------------------------------------------------------
 * // This program is free software; you can redistribute it and/or modify it
 * // under the terms of the GNU Lesser General Public License as published by the
 * // Free Software Foundation; either version 3 of the License, or (at your
 * // option) any later version.
 * // This library is distributed in the hope that it will be useful,
 * // but without any warranty; without even the implied warranty of merchantability
 * // or fitness for a particular purpose.
 * // You should have received a copy of the GNU Lesser General Public License along
 * // with this program; if not, see <http://www.gnu.org/licenses/lgpl.html>.
 * // ---------------------------------------------------------------------------
 */

package pl.bristleback.server.bristle.utils;

import org.apache.log4j.Logger;
import pl.bristleback.server.bristle.exceptions.BristleRuntimeException;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * Utility class that holds information about object getter.
 * Contains information about getter method and field name.
 * <p/>
 * Created on: 2010-11-21 16:37:23 <br/>
 *
 * @author Wojciech Niemiec
 */
public final class Getter {
  private static Logger log = Logger.getLogger(Getter.class.getName());

  private String fieldName;
  private Method getterMethod;

  /**
   * Creates a new Getter object with complete information.
   *
   * @param fieldName    name of the field.
   * @param getterMethod getter method.
   */
  public Getter(String fieldName, Method getterMethod) {
    this.fieldName = fieldName;
    this.getterMethod = getterMethod;
  }

  /**
   * Invokes getter method on the object given as parameter.
   * Any exception while invoking method will cause {@link BristleRuntimeException} to throw.
   *
   * @param bean the object the underlying method is invoked from.
   * @return the result of invoking getter method.
   */
  public Object invoke(Object bean) {
    try {
      return getterMethod.invoke(bean);
    } catch (IllegalAccessException e) {
      throw new BristleRuntimeException(e.getMessage(), e);
    } catch (InvocationTargetException e) {
      throw new BristleRuntimeException(e.getMessage(), e);
    }
  }

  /**
   * Type of object returned by getter method.
   *
   * @return type of object returned by getter method.
   */
  public Class getReturnType() {
    return getterMethod.getReturnType();
  }

  /**
   * Name of the returned field name.
   *
   * @return name of the returned field name.
   */
  public String getFieldName() {
    return fieldName;
  }

  /**
   * Getter method.
   *
   * @return getter method.
   */
  public Method getGetterMethod() {
    return getterMethod;
  }
}
